import React from 'react';
import { Radio, Toast, Icon, Picker, Button, InputItem, List, DatePicker, Flex, Modal, Checkbox } from 'antd-mobile';
import { createForm } from 'rc-form';
import Container from '../../components/Base/Container';
import _ from 'lodash';
import moment from 'moment';
import {fetchPaidVip,
        fetchVipInfo2,
        fetchTags,
        updateProfile,
        bindVipCard
} from '../../services/vipService';
import styles from './VipInfo.less';
const alert = Modal.alert;
const CheckboxItem = Checkbox.CheckboxItem

class VipInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      vips: [],
      loading: false,
      paidVip: null,
      skinRadio: '',
      skinCheckbox: [],
      isAgree: false,
      isVisible: false,
      isVisible2: false,
      skin: [
        {value: '中性', label: '中性', isChecked: false},
        {value: '干性', label: '干性', isChecked: false},
        {value: '油性', label: '油性', isChecked: false},
        {value: '混油', label: '混油', isChecked: false},
        {value: '混干', label: '混干', isChecked: false},
        {value: '敏感', label: '敏感', isChecked: false},
      ],
      skinChange: [
        {value: '大油田', label: '大油田', isChecked: false},
        {value: '干燥起皮', label: '干燥起皮', isChecked: false},
        {value: '毛孔粗大', label: '毛孔粗大', isChecked: false},
        {value: '色斑', label: '色斑', isChecked: false},
        {value: '暗黄', label: '暗黄', isChecked: false},
        {value: '黑头白头', label: '黑头白头', isChecked: false},
        {value: '痘痘痘印', label: '痘痘痘印', isChecked: false},
        {value: '闭口', label: '闭口', isChecked: false},
        {value: '衰老皱纹', label: '衰老皱纹', isChecked: false},
        {value: '皮肤敏感', label: '皮肤敏感', isChecked: false},
        {value: '红血丝', label: '红血丝', isChecked: false},
        {value: '黑眼圈', label: '黑眼圈', isChecked: false},
        {value: '眼袋', label: '眼袋', isChecked: false}
      ]
    };
  }
  
  /* 解绑 */
  exBind = (shopId, card_id, card_no) => {
    alert('', '确定要解绑', [
      { text: '取消', style: 'default' },
      { text: '确定', style: '#3ED2DF', onPress : () => {
        bindVipCard({
          shopId: shopId,
          card_id: card_id,
          card_no: card_no,
          card_bind_status: false,
        }).then( res => {
          console.log('解绑', res)
        })
        localStorage.clear()
        this.props.history.replace(`/third_vipCard?shopId=${shopId}`)
      }},
    ]);
  }
 /* 获取会员资料 */
  getVips = (shopId, card_id, card_no, phone) => {
    fetchVipInfo2(shopId, card_id, card_no, phone).then( res => {
      console.log('获取会员资料', res)
      if (res.data.vips) {
       
         this.setState({
           vips: res.data.vips[0],
           skinRadio: res.data.vips[0].skinType || '无',
           skinCheckbox: res.data.vips[0].skinProblem || ['无']
         })
      }
   })
  }

  /* 获取皮肤标签 */
  getTags = (shopId) => {
    fetchTags(shopId).then( res => {
      console.log('获取皮肤标签', res)
      let {data} = res
      
      let index = data.findIndex( v => v.group_name === '肤质') 
      let indexP = data.findIndex( v => v.group_name === '肤质问题')

      let skin = []
      let skinChange = []

      if (index != -1) {
        skin = data[index].tags.map( v => v = {"value": v, "label": v, "isChecked": false})
      }

      if (indexP != -1) {
        skinChange = data[indexP].tags.map( v => v = {"value": v, "label": v, "isChecked": false})
      }
      this.setState({
        skin,
        skinChange
      })
      
    })
  }

  componentDidMount() {
    const {shopId, phone, card_id, card_no} = this.props.location.query;

    this.getVips(shopId, phone, card_id, card_no)

    this.getTags(shopId)
  }

  componentWillUnmount() {
    clearInterval(this.state.timer);
  }

  /* 收集表单 */
  birSubmit = (birthday) => {
    const {shopId, phone, card_id, card_no} = this.props.location.query;
      // 发起请求
      let that = this
      updateProfile(shopId, card_id, {birthday:birthday.format('YYYYMMDD')}).then(res => {
        if (res.data.success) {
          Toast.success('修改成功', 1)
          that.getVips(shopId, phone, card_id, card_no)
        }else {
          Toast.fail('修改失败', 1)
        }
      }) 
  }
  submitInfo = () => {
    const {shopId, phone, card_id, card_no} = this.props.location.query;
    const {skinRadio, skinCheckbox, isAgree} = this.state
    this.props.form.validateFields((error) => {
      if (!error) {
          let value = this.props.form.getFieldsValue();
          
/*           if (value.mobile) {
            value.mobile = value.mobile.replace(/\s/ig, '');
          }

          if (!skinRadio || skinRadio == ''){
            return Toast.info('请选择肤质')
          }else {
            value.skinRadio = skinRadio
          }
          if (!skinCheckbox || skinCheckbox.length === 0){
            return Toast.info('请选择需要改善的皮肤问题')
          }else {
            value.skinCheckbox = skinCheckbox
          } */
          
          if (value.birthday) {
            /* value.birthday = value.birthday.startOf('day'); */
            value.birthday = value.birthday.format('YYYYMMDD')
          }

          
          // 发起请求
          let that = this
            console.log('表单数据',value)
            updateProfile(shopId, card_id, {birthday:value['birthday']}).then(res => {
              if (res.data.success) {
                Toast.success('修改成功', 1)
                that.getVips(shopId, phone, card_id, card_no)
              }else {
                Toast.fail('修改失败', 1)
              }
            }) 

/*       if (isAgree) {
            
          }else {
            Toast.info('您还没同意推广资讯')
          } */
      } else {
        Toast.fail('验证失败', 1)
      }
    });
  };


  renderHeader = () => {
    return (<div style={{ position: 'relative' }}>
      编辑个人资料
      { this.props.closable &&
      <span
        style={{
          position: 'absolute', right: 3, top: -5,
        }}
        onClick={() => {
          if (this.props.onClose) {
            this.props.onClose();
          }
        }}
      >
        <Icon type="cross" />
      </span>
      }
    </div>);
  };

  /* 肤质 */
  radio = (val) => {
    let {skin} = this.state
    let index = skin.findIndex(v => v.value == val)
    skin.forEach(v => v.isChecked = false)
    skin[index].isChecked = true
    this.setState({
      skin,
      skinRadio: skin[index].value
    })

  }
  
  /* 三个肤质问题 */
  checkbox = (val) => {
    let {skinCheckbox, skinChange} = this.state
    // 表单数组
    let formIndex = skinCheckbox.findIndex( v => v===val)
    // 渲染数组
    let index = skinChange.findIndex(v => v.value===val)

    if (formIndex !== -1 && skinCheckbox.length <= 3) {
      skinChange[index].isChecked = false
      skinCheckbox.splice(formIndex, 1)
    }else if (formIndex === -1 && skinCheckbox.length === 3){
      Toast.info('只能选择三个肤质问题哟', 1.5)
    } else if (formIndex === -1 && skinCheckbox.length < 3) {
      skinCheckbox.push(val)
      skinChange[index].isChecked = true
    }

    this.setState({
      skinChange,
      skinCheckbox
    })

  }

  styleShowSkin = {
    width: '100%',
    height: '1rem',
    lineHeight: '1rem',
    fontWeight: 'bold',
    color: '#333333',
    fontSize: '.386473rem',
    background: '#F2F2F2',
    position: 'absolute',
    left: '0',
    top: '0'
  }
  styleShowSkinBoby = {
    marginTop: '.5rem',
    display: 'flex',
    textAlign: 'center',
    alignItems: 'center',
    flexFlow: 'wrap',
    fontSize: '.326087rem',
  }

  /* skin复选框 */
  showSkinBody = (isChecked) => {
    let data = []
    const {skin, skinChange} = this.state
    if (!isChecked || isChecked === 0) {
      data = skin
      return (
        <div style={this.styleShowSkinBoby}>
          {data.map(i => (
             <div style={{margin: '0 auto', width: '33.33%', boxSizing: 'border-box', paddingLeft: '0.3rem'}} className={styles.pdiv} key={i.value}>
              <CheckboxItem
                checked={i.isChecked}
                onChange={() => this.radio(i.value)}>
                <span style={{color: '#666', fontWeight: 'normal'}}>{i.value}</span>
              </CheckboxItem>
            </div>
          ))}
        </div>
      )
    }else {
      data = skinChange
      return (
        <div style={this.styleShowSkinBoby}>
           {data.map(i => (
             <div style={{width: '33.33%'}} className={styles.checkbox2}>
              <CheckboxItem 
                checked={i.isChecked}
                key={i.value} 
                onChange={() => this.checkbox(i.value)}>
                <span style={{color: '#666', fontWeight: 'normal'}}>{i.label}</span>
              </CheckboxItem>
            </div>
          ))}
        </div>
      )
    }
  }

 /* 同意按钮 */
 handleAgree = () => {
   this.setState({
     isAgree: !this.state.isAgree
   })
 }

 /* 单选取消 */
 radioCancel = () => {
  let {skin} = this.state
  skin.forEach(v => v.isChecked = false)
  this.setState({
    isVisible: false, 
    skinRadio: '',
    skin
  })
 }

 /* 单选取消 */
 radioCancel = () => {
  let {skin} = this.state
  skin.forEach(v => v.isChecked = false)
  this.setState({
    isVisible: false, 
    skinRadio: '',
    skin
  })
 }

 /* 复选取消 */
 checkboxCancel = () => {
  let {skinChange} = this.state
  skinChange.forEach(v => v.isChecked = false)
  this.setState({
    isVisible2: false, 
    skinCheckbox: [],
    skinChange
  })
 }

  render() {
    const {shopId, phone, card_id, card_no} = this.props.location.query;
    (<Modal></Modal>).props.style.width = '85%'
    const { getFieldProps, getFieldError } = this.props.form;
    const {vips} = this.state
    if (this.state.timeLimit > 0) {
      codeBtnClass = 'disableCodeBtn';
    }

    const { paidVip } = this.state;
    let isPaidVip = false;
    if (paidVip && paidVip.enable && paidVip.paidCardTypes && paidVip.paidCardTypes.length) {
      isPaidVip = true;
    }
    /* 门店列表 */
    const branchNo = this.props.branchNo;
    const salemanId = this.props.salemanId;
    return (

    

    <Container title='编辑个人资料'>
      {/* 肤质单选 */}
      <Modal 
        visible={this.state.isVisible}
        transparent
        maskClosable
        title={<div style={this.styleShowSkin}>选择肤质</div>}
        footer={[
          {text: '取消', onPress: () => this.radioCancel()},
          {
            text: '确定', 
            onPress: () => {this.setState({isVisible: false})},
            style: {color: '#3ED2DF'}
          }
        ]}
      >
        {this.showSkinBody(0)}
      </Modal>
      {/* 肤质三个选项 */}
      <Modal 
        visible={this.state.isVisible2}
        transparent
        maskClosable
        title={<div style={this.styleShowSkin}>急需改善的三个皮肤问题</div>}
        footer={[
          {text: '取消', onPress: () => this.checkboxCancel()},
          { 
            text: '确定', 
            onPress: () => {this.setState({isVisible2: false})},
            style: {color: '#3ED2DF'}
          }
        ]}
      >
        {this.showSkinBody(1)}
      </Modal>
    <div>
      <div className="vipRegForm">
     {/*  <Header header={{message: 'testheader'}}></Header> */}
      <List
        className={styles.popupList}
      >
        <InputItem
          error={!!getFieldError('vip_name')}
          {...getFieldProps('vip_name', {
            initialValue: vips.vip_name,
            rules: [{ required: true, message: '请输入您的名字' }],
          })}
          type="text"
          disabled
          style={{height: '1.2rem'}}
        >姓名</InputItem>

        {/* 手机号码 */}
        <InputItem
          error={!!getFieldError('mobile')}
          {...getFieldProps('mobile', {
            initialValue: vips.mobile,
            rules: [{ required: true, message: '请输入您的手机号码' }],
          }) }
          type="phone"
          disabled
          style={{height: '1.2rem'}}
        >手机</InputItem>

        <DatePicker
          mode="date"
          title="选择生日"
          /* moment(moment(vips.birthday).format('YYYYMMDD'), "YYYYMMDD").fromNow() */
          extra={moment(vips.birthday).format('YYYY-MM-DD') || ''}
          value={moment(moment(vips.birthday).format('YYYYMMDD'), "YYYYMMDD").fromNow()}
          maxDate={moment().add(2, 'years')}
          minDate={moment().subtract(12, 'years')}
          {...getFieldProps('birthday', {
            rules: [{ required: true, message: '请选择您的生日' }],
          })}

          onChange = {(e) => this.birSubmit(e)}
        >
          <List.Item arrow="horizontal">生日</List.Item>
        </DatePicker>
        
        {/* 肤质要弹框选择   List.Item arrow="horizontal">肤质</List.Item>*/}
        <div 
         /* onClick={() => {this.setState({isVisible: true})}} */
         >
        <Picker 
          disabled 
          extra={this.state.skinRadio ? this.state.skinRadio : '请选择'}
          >
          <List.Item arrow="horizontal">肤质</List.Item>
        </Picker>
        </div>
        {/* 需要改善的皮肤问题 弹框选择*/}
        <div 
         /*  onClick={() => {this.setState({isVisible2: true})}}  */
          className={styles.lastListItem}
        >
        <Picker 
           disabled
           extra={this.state.skinCheckbox.length !==0 ? this.state.skinCheckbox.join(' ') : '请选择'}
           >
          <List.Item arrow="horizontal" style={{borderBottom: 'none'}}>需要改善的皮肤问题</List.Item>
        </Picker>
        </div>

        {/* 门店 */}
        <InputItem
          error={!!getFieldError('branch_name')}
          {...getFieldProps('branch_name', {
            rules: [{ required: true, message: '门店' }],
            initialValue: vips.branch_name
          }) }
          disabled
          style={{height: '1.2rem'}}
        >门店</InputItem>
        {/* 选择导购 */}
        <InputItem
          error={!!getFieldError('saleman_name')}
          {...getFieldProps('saleman_name', {
            rules: [{ required: true, message: '选择导购' }],
            initialValue: vips.saleman_name
          }) }
          disabled
          style={{height: '1.2rem'}}
        >选择导购</InputItem>
         {/* 住址 */}
         <InputItem
          error={!!getFieldError('vip_add')}
          {...getFieldProps('vip_add', {
            rules: [{ required: true, message: '住址' }],
            initialValue: vips.vip_add
          }) }
          disabled
          style={{height: '1.2rem',borderBottom: '.024rem solid #ccc'}}
        >住址</InputItem>
        {/* 同意按钮 */}
       {/*  <div className={styles.agreeWrap} onClick={()=>{this.handleAgree()}}>
             <span className={this.state.isAgree ? styles.agreeIconSelected :styles.agreeIcon}></span>
             <span> 我同意接受由</span>
             <span>【GLP+】及其【参与商户】所发的市场推广资讯。</span>
        </div> */}
    </List>

      <ul style={{ padding: '.966184rem .531401rem', listStyle: 'none' ,margin: 0}}>
        <li>
          <Button 
            type="primary"  
            style={{border: 'none', height: '1.15942rem',lineHeight: '1.15942rem',fontSize: '.434783rem', background: 'linear-gradient(to bottom, #12D5C8, #19C9DA)', borderRadius: '.144928rem', color: '#fff'}} disabled={this.props.loading} 
            loading={this.props.loading} 
            onClick={() => this.exBind(shopId, card_id, card_no)}
            >
             解除绑定
          </Button>
        </li>

        <li  className={styles.b}>
          会员生日可以修改2次
        </li>
      </ul>
    </div>
    </div>
    </Container>
    );
  }
}

VipInfo.defaultProps = {
  regBtnText: '确定',
  closable: true,
};

export default createForm()(VipInfo);
